
import { MenuInfo } from '@/core/MenuInfo'
import { defineStore } from 'pinia'
import { AppInfo } from '@/core/AppInfo'
import { RouteLocationNormalized } from 'vue-router'

export interface IAppState{
  isCollapse:boolean;
  appInfoList: AppInfo[];
  menuList: MenuInfo[];
  allMenuList: MenuInfo[];
  activeAppCode: string;
  activedApp?: AppInfo;
  routeing: boolean;
}


export const useApplicationStore = defineStore('application', {
  state: ():IAppState => (
    {
      isCollapse: false,
      appInfoList: [],
      menuList: [],
      allMenuList:[],
      activeAppCode: '',
      routeing: false,
      activedApp: undefined
    }
  ),
  actions:({
    collapsed(){
      this.isCollapse=!this.isCollapse
    },
    beforeRouting(){
      this.routeing=true;
    },
    afterRouting(){
      this.routeing=false;
    },
    routeChange(){
      this.routeing = !this.routeing;
    },
    setMenuAndApp(appList:AppInfo[], menuList: MenuInfo[]){
      this.appInfoList=[
        ...appList
      ]
      this.allMenuList=[
        ...menuList
      ]

      const lastApp = this.$cache.getCache('ACTIVE_APP') as AppInfo
      const lastRouterFullPath = this.$cache.getCache('LAST_ROUTER_FULLPATH') as RouteLocationNormalized;
      
      if(lastApp && lastRouterFullPath){
        this.activeApp(lastApp)
        this.$router.replace(lastRouterFullPath)
        return;
      }
      
      if(appList.length){
        this.activeApp(appList[0])
      }
    },
    toFirst(){
      console.log('all router:', this.$router.getRoutes());
      this.$router.replace(this.menuList[0].link)
    },
    activeApp(app:AppInfo){
      this.$cache.cache('ACTIVE_APP', app)
      this.activedApp=app
      this.menuList = this.allMenuList.filter(c=>c.meta.app===app.code)
      this.activeAppCode = app.code
      this.$dynamicRouter(app.code)
      this.toFirst()
    }
  })
})